package toDoList.Controllers;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import toDoList.Manager.DataBaseHelper;
import toDoList.Manager.R;
import toDoList.Manager.R.id;
import toDoList.Manager.R.layout;
import toDoList.Models.UserModel;

import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

public class UserController extends Activity implements ControllerInterface {

	private SQLiteDatabase db;
	DataBaseHelper helper;
	public String errors;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user);
        helper = new DataBaseHelper(this);
        db = helper.getReadableDatabase();
    }

	/**
	 * createListener(): Used just to link classes together through the controllerInterface interface
	 */
	public void createListener()
	{
		throw new UnsupportedOperationException("The method is not implemented yet.");
	}
	
	/**
	 * isEmail(String email) Returns true if the "email" parameter is an actual email
	 * @param email The email to input
	 * @return
	 */
	public boolean isEmail(String email)
	{
	    boolean matchFound1;
	    boolean returnResult=true;
	    email=email.trim();
	    if(email.equalsIgnoreCase(""))
	        returnResult=false;
	    else if(!Character.isLetter(email.charAt(0)))
	        returnResult=false;
	    else 
	    {
	        Pattern p1 = Pattern.compile("^\\.|^\\@ |^_");
	        Matcher m1 = p1.matcher(email.toString());
	        matchFound1=m1.matches();

	        Pattern p = Pattern.compile("^[a-zA-z0-9._-]+[@]{1}+[a-zA-Z0-9]+[.]{1}+[a-zA-Z]{2,4}$");
	        // Match the given string with the pattern
	        Matcher m = p.matcher(email.toString());

	        // check whether match is found
	        boolean matchFound = m.matches();

	        StringTokenizer st = new StringTokenizer(email, ".");
	        String lastToken = null;
	        while (st.hasMoreTokens()) 
	        {
	            lastToken = st.nextToken();
	        }
	        if (matchFound && lastToken.length() >= 2
	        && email.length() - 1 != lastToken.length() && matchFound1==false) 
	        {

	           returnResult= true;
	        }
	        else returnResult= false;
	    }
	    return returnResult;
	 }
	
	/**
	 * okPressed(View view) Goes back to the login page, sending the data from the text fields (error checking is processed here too)
	 * @param view Null
	 */
	public void okPressed(View view)
	{
		Intent data = new Intent();
		
		boolean filled = true;
		String errors = "";
		
		if(((EditText)findViewById(R.id.nameUserText)).getText().toString().length() > 20)
		{
			errors += "Name must be less than 20 characters. ";
			filled = false;
		}
		if(((EditText)findViewById(R.id.nameUserText)).getText().toString().equals(""))
		{
			errors += "Name field must be filled in. ";
			filled = false;
		}
		if(((EditText)findViewById(R.id.passwordUserText)).getText().toString().equals("") || ((EditText)findViewById(R.id.retypePasswordUserText)).getText().toString().equals("") || !((EditText)findViewById(R.id.retypePasswordUserText)).getText().toString().equals(((EditText)findViewById(R.id.passwordUserText)).getText().toString()) )
		{
			errors += "Password fields do not match. ";
			filled = false;
		}
		if(((EditText)findViewById(R.id.emailUserText)).getText().toString().equals("") || ((EditText)findViewById(R.id.retypeEmailUserText)).getText().toString().equals("") || !((EditText)findViewById(R.id.retypeEmailUserText)).getText().toString().equals(((EditText)findViewById(R.id.emailUserText)).getText().toString()) )
		{
			errors += "Email fields do not match. ";
			filled = false;
		}
		if(!isEmail(((EditText)findViewById(R.id.emailUserText)).getText().toString()))
		{
			errors += "Email must be valid. ";
			filled = false;
		}
		
		if(filled == false)
		{
			popUp(errors);
			this.errors = errors;
		}
		else if(filled == true)
		{
			String email = null;
			
			try
			{
				email = getUserByEmail(((EditText)findViewById(R.id.emailUserText)).getText().toString()).getString(0);
			}
			catch(Exception e)
			{
				
			}
			
			if(email == null)
			{
			    data.putExtra("name", ((EditText)findViewById(R.id.nameUserText)).getText().toString());
				if(((EditText)findViewById(R.id.emailUserText)).getText().toString().equals(((EditText)findViewById(R.id.retypeEmailUserText)).getText().toString()))
					data.putExtra("email", ((EditText)findViewById(R.id.emailUserText)).getText().toString());
				if(((EditText)findViewById(R.id.passwordUserText)).getText().toString().equals(((EditText)findViewById(R.id.retypePasswordUserText)).getText().toString()))
					data.putExtra("password", ((EditText)findViewById(R.id.passwordUserText)).getText().toString());
			    setResult(Activity.RESULT_OK, data);
		        finish();
			}
			else
			{
				popUp("User already exists");
			}
		}
	}
	
	/**
	 * cancelPressed(View view) Goes back to the login page, without sending any data
	 * @param view Null
	 */
	public void cancelPressed(View view)
	{
		Intent intent = new Intent();
        setResult(RESULT_CANCELED, intent);
        finish();
	}

	/**
	 * popUp(String n) Displays a pop-up window with the message "n" inside of it.
	 * @param n
	 */
	public void popUp(String n) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(n)
		       .setCancelable(false)
		       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		
		builder.show();
	}

	/**
	 * getUserByEmail(String email) Gets the user data from the database using their email
	 * @param email The email to search with
	 * @return A cursor with the data of the user
	 * @throws SQLException
	 */
	public Cursor getUserByEmail(String email) throws SQLException {
		
	    db = helper.getReadableDatabase();
		
	    Cursor mCursor =		
	      db.query(true, "User", new String[] {"name",
	          "email", "password"}, "email" + " = " + "'" + email + "'", null,
	          null, null, null, null);
	    if (mCursor != null) {
	      mCursor.moveToFirst();
	    }
	    db.close();
	    return mCursor;
	 
	  }
	
}